import { fromCallback, checkError } from '../../universalify'
import fs from '../fs'
import path from '../../node/path'
import mkdir from '../mkdirs'
import pathExists from '../path-exists'
import { LogUtil } from '../../../LogUtil'

function outputFile (file, data, encoding?, callback?) {
    try {
        LogUtil.info('outputFile');
        if (typeof encoding === 'function') {
            callback = encoding
            encoding = { encoding: 'utf-8' }
        }

        const dir = path.dirname(file)
        pathExists.pathExists(dir, (err, itDoes) => {
            if (checkError(err)) return callback(err)
            if (itDoes) return fs.writeFile(file, data, encoding, callback)

            mkdir.mkdirs(dir, err => {
                if (checkError(err)) return callback(err)

                fs.writeFile(file, data, encoding, callback)
            })
        })
    } catch (e) {
        LogUtil.error('outputFile error: %{public}s', e.message);
    }
}

function outputFileSync (file, data, options?) {
    try {
        LogUtil.info('outputFileSync');
        const dir = path.dirname(file)
        if (pathExists.pathExistsSync(dir)) {
            return fs.writeFileSync(file, data, options)
        }
        mkdir.mkdirsSync(dir)
        fs.writeFileSync(file, data, options)
    } catch (e) {
        LogUtil.error('outputFileSync error: %{public}s', e.message);
    }

}

export default {
    outputFile: fromCallback(outputFile),
    outputFileSync
}
